<?php

class RoleController extends Controller
{
    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionGetdata(){

        $page = $_REQUEST['page'];
        $rows = $_REQUEST['rows'];
        $start = ($page-1)*$rows;
        $total = $this->connection->createCommand("select count(1) from sys_authitem where type = 2 and deleted = 0 ")->queryScalar();
        $result = $this->connection->createCommand("select * from sys_authitem where type = 2  and deleted = 0  limit {$rows} offset {$start}")->queryAll();

        $data = Array();
        $data['total'] = $total;
        $data['rows'] = $result;

        echo json_encode($data);
    }

    public function actionRemove(){
        $name = $_REQUEST['name'];
        $this->connection->createCommand("update sys_authitem set deleted = 1 
where name = :name and type = 2")
            ->bindParam(':name',$name,PDO::PARAM_INT)
            ->execute();
    }

    /**
     * 获取用户的权限
     */
    public function actionGetuserroles(){
        $userid = $_REQUEST['userid'];

        //获取所有的权限
        $roles = $this->connection->createCommand("select * from sys_authitem where type = 2  and deleted = 0")->queryAll();
        //获取用户的权限
        $userroles = $this->connection->createCommand("select itemname from sys_authassignment where userid = :userid")
            ->bindParam(':userid',$userid,PDO::PARAM_STR)
            ->queryAll();
        $userrolesarray = array();
        foreach ($userroles as $ur){
            $userrolesarray[] = $ur['itemname'];
        }

        $treedata = array();
        foreach($roles as $r){
            if(in_array($r['name'],$userrolesarray)){
                $treedata[] = array('id'=>$r['name'],'text'=>$r['name'],'checked'=>true);
            }else{
                $treedata[] = array('id'=>$r['name'],'text'=>$r['name'],'checked'=>false);
            }
        }

        echo json_encode($treedata);
    }

    public function actionShowedit(){

        $name = $_REQUEST['name'];

        $role = null;
        if(is_null($name)){
            //新增
        }else{
            //编辑
            $role = $this->connection->createCommand("select * from sys_authitem where name = :name")->bindParam(':name',$name,PDO::PARAM_STR)->queryRow();
        }

        //获取权限数据
        $items = $this->connection->createCommand("select * from sys_authitemchild where parent = :name")->bindParam(':name',$name,PDO::PARAM_STR)->queryAll();

        $this->render('showedit',['role'=>$role,'item'=>$items]);
    }

    public function actionSavedata(){
        $name = $_REQUEST['name'];
        $description = $_REQUEST['description'];
        $accesskeys = $_REQUEST['accesskeys'];

        $auth = Yii::app()->authManager;

        $role = null;
        //查询是否存在，如果存在，则进行编辑操作，不存在，则进行修改
        $exist = $this->connection->createCommand("select * from sys_authitem where name = :name")->bindParam(':name',$name,PDO::PARAM_STR)->queryRow();
        if($exist==null){
            $role=$auth->createRole($name,$description);
        }else{
            $role=$role=$auth->getRoles()[$name];
        }

        $this->connection->createCommand("delete from sys_authitemchild where parent = :name")->bindParam(':name',$name,PDO::PARAM_STR)->execute();

        $accesskeyslist = explode(",", $accesskeys);
        foreach ($accesskeyslist as $ac){
            $role->addChild($ac);
        }

    }

    /**
     * 导入权限项目
     *
     * http://open.crm.com/y.php?r=settings/role/importoperation
     *
     */
    public function actionImportoperation(){

        $json = file_get_contents("E:/php/open-crm/website/protected/modules/settings/config/roletree.js");
        $jsonobject = json_decode($json);

        $this->importOperation($jsonobject);
    }

    private function importOperation($roletree){
        $auth = Yii::app()->authManager;
        foreach($roletree as $ob){
            echo $ob->attributes->accesskey;
            if($ob->attributes->accesskey!=null){
                //判断数据库权限是否存在，不存在则进行插入操作
                $exist = $this->connection->createCommand("select * from sys_authitem where name = :name and type = 0")->bindParam(':name',$ob->attributes->accesskey,PDO::PARAM_STR)->queryRow();
                if($exist == null){
                    $auth->createOperation($ob->attributes->accesskey,$ob->text);
                }

                if(isset($ob->children)){
                    $this->importOperation($ob->children);
                }
            }
        }
    }

    public function actionTree(){
        //查询数据权限
        $connection = $this->connection;
        $menus = $connection->createCommand("select menupermission as id,menutext as text,menupermission as accesskey,menu_id from sys_menu where type = 'menu' ORDER BY seq desc ")->queryAll();
        foreach ($menus as &$menu){
            $menuobj = $menu;
            $menu['attributes'] = $menuobj;
            $menu_chirdren = $connection->createCommand("select menupermission as id,menutext as text,menupermission as accesskey,menu_id from sys_menu where type = 'menuitem' and parent_id = {$menu['menu_id']} ORDER BY seq desc ")->queryAll();
            foreach($menu_chirdren as &$menu_chird){
                $menu_chird_obj = $menu_chird;
                $menu_chird['attributes'] = $menu_chird_obj;
                $module_chirdren = $connection->createCommand("select menupermission as id,menutext as text,menupermission as accesskey,menu_id from sys_menu where type = 'module' and parent_id = {$menu_chird['menu_id']} ORDER BY seq desc ")->queryAll();
                $menu_chird['children'] = $module_chirdren;
                foreach ($module_chirdren as &$module_child){
                    $module_child_obj = $module_child;
                    $module_child['attributes'] = $module_child_obj;
                }
//                $menu_chirdren['chirdren'] = $menu_chird;
            }
            $menu['children'] =$menu_chirdren;
        }
        echo json_encode($menus);

        /*$myfile = fopen("D:/zhujun/php/crm_tools/web/website/protected/modules/settings/config/roletree.js", "r") or die("Unable to open file!");
        $list = fread($myfile,filesize("D:/zhujun/php/crm_tools/web/website/protected/modules/settings/config/roletree.js"));
        fclose($myfile);

        $list = json_decode($list);
        foreach ($list as $l){
            $this->connection->createCommand("insert into sys_menu (menutext,menupermission,`type`,parent_id) values
 ('{$l->text}','{$l->id}','menu',0) ")->execute();
            $menu_insertid = $this->connection->getLastInsertID();
            //menuitem
            foreach ($l->children as $mi){
                $this->connection->createCommand("insert into sys_menu (menutext,menupermission,`type`,parent_id) values
 ('{$mi->text}','{$mi->id}','menuitem',{$menu_insertid}) ")->execute();
                $menuitem_insertid = $this->connection->getLastInsertID();
                if(isset($mi->children)){
                    foreach ($mi->children as $mo){
                        $this->connection->createCommand("insert into sys_menu (menutext,menupermission,`type`,parent_id) values
 ('{$mo->text}','{$mo->id}','module',{$menuitem_insertid}) ")->execute();
                    }
                }
            }
        }*/
//        print_r($list);
//        ;
    }
}